package com.hsgene.shoppingcar.service.impl;

import com.hsgene.common.util.character.CharactersConstant;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.shoppingcar.domain.ShoppingCarInfo;
import com.hsgene.shoppingcar.dto.SelectedPriceAndCountInfo;
import com.hsgene.shoppingcar.dto.ShoppingCarInfoDto;
import com.hsgene.shoppingcar.dto.ShoppingCarListInfo;
import com.hsgene.shoppingcar.persistence.ShoppingCarPersistence;
import com.hsgene.shoppingcar.service.ShoppingCarService;
import com.hsgene.shoppingcar.service.api.GeneratorService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车业务层
 *
 * @Author: wangxuefeng@hsgene.com
 * @Description:
 * @Date: Created in 15:50 2018/7/16
 * @Modified By:
 */
@Service
public class ShoppingCarServiceImpl implements ShoppingCarService {

    /**
     * LOG
     */
    private static Logger LOGGER = LogManager.getLogger(ShoppingCarServiceImpl.class);

    @Resource
    private ShoppingCarPersistence shoppingCarPersistence;

    @Resource
    private GeneratorService generatorService;

    /**
     * 加入购物车
     *
     * @param carInfo 商品信息
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public int insert(ShoppingCarInfo carInfo) {
        //id
        ApiResult<GeneratorDto> generatorResult = generatorService.generate("shopping_car", null);
        if (!generatorResult.isSucc()) {
            return 0;
        }
        carInfo.setSelected(false);
        carInfo.setId(generatorResult.getData().getSerialNumber());
        return shoppingCarPersistence.insertAndUpdate(carInfo);
    }

    /**
     * 查询购物车
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public Map<String, Object> queryShoppingCarByUserId(String userId) {
        return getCarListResultMap(userId);
    }

    /**
     * 删除购物车
     *
     * @param shoppingCarId 购物车ID
     * @param userId        用户id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public Map<String, Object> deleteShoppingCar(String shoppingCarId, String userId) {
        //包含逗号,说明是批量删除
        if (shoppingCarId.contains(CharactersConstant.COMMA_EN)) {
            shoppingCarPersistence.deleteBatch(StringUtils.split(shoppingCarId, CharactersConstant.COMMA_EN));
        }
        shoppingCarPersistence.deleteByPrimaryKey(shoppingCarId);
        //获取列表
        return getCarListResultMap(userId);
    }

    /**
     * 更新购物车
     *
     * @param infoDtoList 更新信息
     * @param userId      用户id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public Map<String, Object> updateShoppingCar(List<ShoppingCarInfoDto> infoDtoList, String userId) {
        boolean result = shoppingCarPersistence.updateShoppingCar(infoDtoList);
        if (!result) {
            return new HashMap<>();
        }
        return getCarListResultMap(userId);
    }

    /**
     * 获取列表和总价
     *
     * @param userId 用户id
     * @return
     */
    private Map<String, Object> getCarListResultMap(String userId) {
        Map<String, Object> map = new HashMap<>();
        LOGGER.info("get shopping car list info...");
        //获取总价格
        SelectedPriceAndCountInfo spaci = shoppingCarPersistence.getShoppingCarSelectedPrice(userId);
        LOGGER.info("get shopping car restlt is :" + spaci);
        if (spaci != null) {
            map.put("sumPrice", spaci.getSumPrice() == null ? 0.00 : spaci.getSumPrice());
            map.put("selectCount", spaci.getSelectCount());
        } else {
            map.put("sumPrice", 0.00);
            map.put("selectCount", 0);
        }
        //列表
        List<ShoppingCarListInfo> carListInfos = shoppingCarPersistence.queryShoppingCarByUserId(userId);
        map.put("carList", carListInfos);
        return map;
    }
}
